package system

import (
	"context"
	"fmt"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/system/parameter"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
	"strings"
)

type OrgService struct{ orgDao string }

func init() {
	orgService := OrgService{
		orgDao: "system.OrgDao",
	}
	factory.Put(reflect.TypeOf(orgService).String(), &orgService)
}
func (s *OrgService) GetOrgDao() *OrgDao {
	return factory.Get(s.orgDao).(*OrgDao)
}
func (s *OrgService) GetOrgCombox(ctx context.Context, req *parameter.GetOrgComboxReq) (res *parameter.GetOrgComboxRes) {
	orgInfos := s.GetOrgDao().GetOrgCombox(ctx, req)
	return &parameter.GetOrgComboxRes{
		Detail: orgInfos,
	}
}
func (s *OrgService) GetOrgTree(ctx context.Context, req *parameter.GetOrgTreeReq) (res *parameter.GetOrgTreeRes) {
	orgInfos := s.GetOrgDao().GetOrgTree(ctx, req)
	orgInfos = s.getOrgTreeRecursive(orgInfos, 0)
	return &parameter.GetOrgTreeRes{
		Detail: orgInfos,
	}
}
func (s *OrgService) getOrgTreeRecursive(list []*parameter.OrgTreeRes, pId uint) []*parameter.OrgTreeRes {
	res := make([]*parameter.OrgTreeRes, 0)
	for _, v := range list {
		if v.PId == pId {
			v.Children = s.getOrgTreeRecursive(list, v.Id)
			res = append(res, v)
		}
	}
	return res
}
func (s *OrgService) ListOrg(ctx context.Context, req *parameter.ListOrgReq) (res *parameter.ListOrgRes) {
	if req.Page <= 1 {
		req.Page = 1
	}
	if req.Size == 0 {
		req.Size = 10
	}
	org := s.GetOrgDao().ListOrg(ctx, req)
	count := s.GetOrgDao().CountOrg(ctx, req)
	res = &parameter.ListOrgRes{
		Total:  count,
		Detail: org,
	}
	return res
}
func (s *OrgService) SaveOrg(ctx context.Context, req *parameter.SaveOrgReq) (res *parameter.SaveOrgRes) {
	//开启事务
	tx, err := s.GetOrgDao().DB().Begin(ctx)
	defer func() {
		if err != nil {
			err := tx.Rollback()
			if err != nil {
				return
			}
			fmt.Println("事务回滚")
			panic("保存机构失败")
		} else {
			err := tx.Commit()
			if err != nil {
				return
			}
			fmt.Println("事务提交")
		}
	}()

	orgIdNum := s.GetOrgDao().CountByOrgName(ctx, req.ParentId, strings.TrimSpace(req.OrgName))

	if req.OrgId > 0 {
		if orgIdNum > 1 {
			panic("机构" + req.OrgName + "已存在！")
		}
		s.GetOrgDao().UpdateOrg(tx, req)
		res = &parameter.SaveOrgRes{OrgId: gconv.Uint(req.OrgId)}
	} else {
		if orgIdNum > 0 {
			panic("机构" + req.OrgName + "已存在！")
		}
		res = s.GetOrgDao().CreateOrg(tx, req)
	}
	return res
}
